<template>
  <div class="home">
    <heads>图书商城</heads>
    <h4 @click="$router.push('/search')" class="search">跳转搜索页面</h4>
    <h4 @click="$router.push('/cell')" class="search">跳转收藏页面</h4>
    <button @click="sorttime">根据修改时间排序</button>
    <ul class="con">
      <li
        v-for="(item, index) in list"
        :key="item.id"
        @click="edit(item, index)"
      >
        <img :src="item.img" alt="" />

        <h6 class="desc">{{ item.desc }}</h6>
        <h5 class="name">
          <p>{{ item.name }}</p>

          <span @click.stop="add(item)">+</span>
        </h5>
      </li>
    </ul>

    <van-popup v-model="show" class="popup">
      <textarea name="" id="" cols="20" rows="5" v-model="editValue"></textarea>
      <button @click="update">确定</button>
    </van-popup>
  </div>
</template>

<script>
// @ is an alias to /src
import heads from "@/components/Header.vue";

export default {
  data() {
    return {
      list: [],
      //所有的列表数据
      val: "",
      //搜索关键字，一开始是空 在mounted中定义如果路由有传参的话就为路由的传参
      show: false, //定义弹出层的显示隐藏
      editValue: "",
      editIndex: -1,
    };
  },

  components: {
    heads,
  },
  mounted() {
    if (this.$route.query.val) {
      this.val = this.$route.query.val;
    }
    //如果有路由传参的话就等于路由的传参，没有的话就是空

    this.$axios.get("data.json").then((res) => {
      console.log(res);

      this.list = res.data.filter((item) => {
        return item.name.includes(this.val);
      });
      //根据搜索关键字进行搜索，如果是第一次进入首页搜索关键字就是空 就会搜到所有的数据
    });
  },
  methods: {
    edit(item, index) {
      this.show = true;
      this.editValue = item.desc;
      this.editIndex = index;
    },
    //点击编辑 展示弹框 回填数据 并且保存要编辑的下标
    update() {
      this.list[this.editIndex].desc = this.editValue;
      this.show = false;
      this.list[this.editIndex].time = new Date();
    },
    //点击确定 根据保存的下标修改数据并且让弹框隐藏

    add(item) {
      this.$store.commit("add", item);
    },
    sorttime() {
      this.list.sort((a, b) => {
        return new Date(b.time) - new Date(a.time);
      });
    },
  },
};
</script>
<style lang="scss">
.search {
  text-align: center;
}
.con {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  li {
    width: 48%;

    box-shadow: 5px 5px 10px rgb(95, 91, 91);
    text-align: center;
    color: rgb(95, 91, 91);
    margin-bottom: 30px;
    img {
      width: 80%;
      height: 200px;
    }
  }
}
.popup {
  padding: 30px;
  button: {
    display: inline-block;
  }
}
.desc {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  height: 2em;
}
.name {
  display: flex;
  justify-content: space-between;
  height: 40px;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
  span {
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    background: chocolate;
    border-radius: 50%;
  }
}
</style>
